package cn.live.kyle.privatealbum;

import java.io.File;
import java.io.OutputStream;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;

public class MainActivity extends Activity {
	private static final String TAG = MainActivity.class.getSimpleName();
	
	public static final int REQUEST_CODE_CAPTURE = 100;

	private static final String DEFAULT_FILE_NAME = "testPhoto.jpg";

	private File mPhotoFile;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_camera) {
			toCapturePhoto();
			return true;
		} else if (id == R.id.action_send) {
			sendPhoto();
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		switch (requestCode) {
		case REQUEST_CODE_CAPTURE:
			if (resultCode == Activity.RESULT_OK) {
				onCapturedPhoto(data);
			}
			break;

		default:
			break;
		}
	}

	private void toCapturePhoto() {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		startActivityForResult(intent, REQUEST_CODE_CAPTURE);
	}

	private void onCapturedPhoto(Intent data) {
		Bitmap photo = (Bitmap) data.getExtras().get("data");

		ImageView imageView = (ImageView) findViewById(R.id.imageView1);
		imageView.setImageBitmap(photo);

		OutputStream os = null;
		try {
			os = openFileOutput(DEFAULT_FILE_NAME, Context.MODE_PRIVATE);
			photo.compress(Bitmap.CompressFormat.JPEG, 100, os);
		} catch (Exception e) {

		} finally {
			try {
				os.flush();
				os.close();
			} catch (Exception e) {

			}
		}
	}

	private void sendPhoto() {
		mPhotoFile = new File(getBaseContext().getFilesDir(), DEFAULT_FILE_NAME);
		if(mPhotoFile.exists()){
			Log.d(TAG, "photo is exists");
		}
		
		Intent intent = new Intent();
		intent.setAction(Intent.ACTION_VIEW);
		intent.setDataAndType(Uri.fromFile(mPhotoFile), "image/*");
	}

}
